package com.wanmait.employment.webController;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wanmait.employment.entity.Company;
import com.wanmait.employment.entity.Publisher;
import com.wanmait.employment.mapper.PublisherMapper;
import com.wanmait.employment.service.PublisherService;
import com.wanmait.employment.util.AjaxResult;
import com.wanmait.employment.util.JWTUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/web/Publisher")
@CrossOrigin
public class WebPublisherController {
    @Resource
    private PublisherService publisherService;
    @Resource
    private PublisherMapper publisherMapper;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Value("${hash.algorithmName}")
    private String algorithmName;
    @Value("${hash.iterations}")
    private Integer iterations;

    //有关公司前台主页公司人事
    @GetMapping("searchPublisher")
    public AjaxResult searchPublisher(Integer companyId){
        List<Publisher> publisherList=publisherService.searchList(companyId);
        return AjaxResult.success("success",publisherList);

    };
    @GetMapping("register")
    public AjaxResult register(String tel,String password) throws JsonProcessingException {
        Publisher publisher=new Publisher();
        publisher.setPassword(password);
        publisher.setTel(tel);

        ObjectMapper objectMapper =new ObjectMapper();
        String jsonstr= objectMapper.writeValueAsString(publisher);
        stringRedisTemplate.opsForValue().set("publisher",jsonstr);
        String salt= UUID.randomUUID().toString().replaceAll("-","");
        publisher.setSalt(salt);
        SimpleHash simpleHash=new SimpleHash(algorithmName,publisher.getPassword(),salt,iterations);
        publisher.setPassword(simpleHash.toString());
        publisherService.register(publisher);
        Publisher publisher1 = publisherService.login(publisher);
        if(publisher1==null){
            return AjaxResult.error(10001,"登录失败了");
        }
        //生成token
        Map<String,String> claims = new HashMap<>();
        claims.put("username",publisher.getPublishername());
        claims.put("name",publisher.getTel());
        String token  = JWTUtils.createToken(publisher.getId()+"",60,publisher.getPassword(),claims);

        //使用token作为键，把admin用户对象放到redis中，设置过期时间和token的过期时间一致
        redisTemplate.opsForValue().set("token:"+token,publisher1,60, TimeUnit.MINUTES);

        publisher1.setPassword(null);
        return AjaxResult.success("注册成功").put("token",token).put("publisher",publisher1);
    }
    @GetMapping("login")
    public AjaxResult login(String tel,String userpass){
        Publisher publisher=new Publisher();
        publisher.setTel(tel);
        publisher.setPassword(userpass);
        Publisher publishers= publisherMapper.selecttel(publisher.getTel());
        //加密
        SimpleHash simpleHash = new SimpleHash(algorithmName,publisher.getPassword(),publishers.getSalt(),iterations);
        publisher.setPassword(simpleHash.toString());
        Publisher publisher1 = publisherService.login(publisher);
        if(publisher1==null){
            return AjaxResult.error(10001,"登录失败了");
        }
        //生成token
        Map<String,String> claims = new HashMap<>();
        claims.put("publishername",publisher.getTel());
        claims.put("publisher",publisher.getPassword());
        String token  = JWTUtils.createToken(publisher.getId()+"",60,publisher.getPassword(),claims);

        //使用token作为键，把admin用户对象放到redis中，设置过期时间和token的过期时间一致
        redisTemplate.opsForValue().set("token:"+token,publisher1,60, TimeUnit.MINUTES);

        publisher1.setPassword(null);
        return AjaxResult.success("登录成功").put("token",token).put("publisher",publisher1);
    }

    @PostMapping("saveOrUpdate")
    public AjaxResult saveOrUpdate( @RequestBody Publisher publisherForm){
        System.out.println(publisherForm+"----****---");
        publisherService.saveOrUpdate(publisherForm);
        return AjaxResult.success("success");
    }

    @PostMapping("uploadDefault")
    public AjaxResult uploadDefault(String avatarName,@RequestBody Publisher loginId){
        System.out.println(avatarName+"文件名称");
        System.out.println(loginId+"文件名称");
        return AjaxResult.success();
    }
    //添加hr 头像
    @PostMapping("upload")
    public AjaxResult upload(MultipartFile file,@RequestBody Publisher obj){
        System.out.println(file);
        if(file==null || file.isEmpty()){
            return AjaxResult.error("没有提交上传文件");
        }
        //检查大小和类型
        try {
            //物理路径
            String realPath= ResourceUtils.getURL("classpath:").getPath()+"static/image";
            //String realPath= "d:/uploadImages";
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            String fileName = UUID.randomUUID().toString().replaceAll("-","")+"."+ext;
            obj.setFace(realPath+ext);
            file.transferTo(new File(realPath,fileName));
            return AjaxResult.success("上传成功").put("fileName",fileName);
        } catch (IOException e) {
            return AjaxResult.error("上传文件失败");
        }
    }


}
